package net.gldwork.facadegen.rt;

import java.io.File;
import java.io.FilenameFilter;
import java.util.List;
import java.util.ResourceBundle;

import net.gldwork.facadegen.annotations.Facade;
import net.gldwork.facadegen.util.PackageUtil;
import net.gldwork.facadegen.util.SPUtil;
import net.gldwork.srcpdr.SourceProducer;

import org.apache.commons.lang3.StringUtils;

public class FacadeGenRuntime {

	public static String[] SCAN_FOLDERS = null;

	public static final String OFF = "off";
	public static final String ON = "on";
	private static String WEBINF_PATH = null;

	public static void generate() {
		/*
		 * init
		 */
		ResourceBundle rb = ResourceBundle.getBundle("facadegen-rt-conf");
		String swi = rb.getString("generate.switch");
		if (OFF.equals(swi)) {
			return;
		}
		SPUtil.FACADE_CLASSNAME = rb.getString("facade.classname");
		SPUtil.FACADE_PKG = rb.getString("facade.package");
		SPUtil.FACADE_SUPERCLASS = rb.getString("facade.superclass");
		SCAN_FOLDERS = rb.getString("scan.folders").split(",");
		String currPath = FacadeGenRuntime.class.getResource("").toString();
		WEBINF_PATH = currPath.substring(currPath.indexOf(":/") + 2,
				currPath.indexOf("WEB-INF/") + 8);
		// scan();
		List<String> cls = PackageUtil.getClassInPackage("com");
		for (String s : cls) {
			System.out.println(s);
		}
	}

	private static String convertPackage(String folder) {
		String path = null;
		if (folder.startsWith("classes/"))
			path = folder.substring(folder.indexOf("classes/") + 8);
		else
			path = folder.substring(folder.indexOf(".jar/") + 5);
		return StringUtils.join(path.split("/"), ".");
	}

	private static void scan() {
		class MyFileNameFilter implements FilenameFilter {

			@Override
			public boolean accept(File dir, String name) {
				if (name.endsWith(".class")) {
					return true;
				}
				return false;
			}

		}
		MyFileNameFilter mff = new MyFileNameFilter();
		SourceProducer sp = SPUtil.initSourceProducer();
		for (String folder : SCAN_FOLDERS) {
			String path = WEBINF_PATH + folder;
			String pkg = convertPackage(folder);
			File f = new File(path);
			if (f.exists() && f.isDirectory()) {
				String[] fileNames = f.list(mff);
				for (String fn : fileNames) {
					try {
						Class<?> clazz = Class.forName(pkg + "."
								+ fn.substring(0, fn.indexOf(".class")));
						populateClass(clazz, sp);
					} catch (ClassNotFoundException e) {

						e.printStackTrace();
					}
				}

			} else {
				System.out.println("FacadeGenerator错误：目录" + path + "不存在");
			}
		}
	}

	private static void populateClass(Class<?> clazz, SourceProducer sp) {
		if (!clazz.isAnnotationPresent(Facade.class)) {
			return;
		}
		System.out
				.println("0----------------------" + clazz.getCanonicalName());

	}

}
